/**
 * interceptors 
 * @description 拦截器配置
 * @Author dinghao
 * @Date 2024-01-01
 * VUE 2.0
 */

import Request from '@/common/service/request.js'
import sysConfig from '@/common/config/config.js'

//设置全局访问的url
const url = sysConfig.congifService.apiUrl

//设置访问token
//const token = uni.getStorageSync('token');
const getTokenStorage = () => {
	let token = ''
	try {
		if(uni.getStorageSync('token')!=null){
			token = uni.getStorageSync('token');
		}else{
			token = ''
		}
	} catch (e) {
		//TODO handle the exception
		console.log("getTokenStorage", e)
	}
	return token
}

//准备http请问
const http = new Request()

//客户端id 
const clientId = sysConfig.congifService.client

/* 设置全局配置 */
http.setConfig((config) => {
	config.baseUrl = url
	config.header = {
		...config.header
	}
	return config
})

/**
 * 自定义验证器
 * @param { Number } statusCode - 请求响应体statusCode（只读）
 * @return { Boolean } 如果为true,则 resolve, 否则 reject
 */
http.validateStatus = (statusCode) => {
	switch (statusCode) {
		case 401:
			uni.showToast({
				title: '登录已过期，请重新登录',
				icon: 'none',
				complete: () => {
					setTimeout(() => {
						uni.navigateTo({
							url:'/pages/index/login'
						})
					}, 1000); // 延迟1秒后跳转
				}
			})
			return false
			break
		case 500:
			uni.showToast({
				title: '服务器异常',
				icon: 'error'
			})
			return false
			break
		case 200:
			return true
	}
}

/* 请求之前拦截器 */
http.interceptor.request((config) => {
	config.header = {
		...config.header,
		'Clientid':clientId,
		//'Authorization': token
		'Authorization': getTokenStorage()
	};
	uni.showLoading({
		title: '加载中',
		mask: true
	});
	return config;
})

/* 请求之后拦截器 */
http.interceptor.response((response) => {
	uni.hideLoading();
	switch (response.data.code) {
		case 401:
			uni.showToast({
				title: '登录已过期，请重新登录',
				icon: 'none',
				complete: () => {
					setTimeout(() => {
						uni.navigateTo({
							url:'/pages/index/login'
						})
					}, 1000); // 延迟1秒后跳转
				}
			})
			break
		case 403:
			uni.showToast({
				icon:'error',
				title:'拒绝访问'
			})
			break
		case 500:
			return response	
		case 400:
			return response	
		case 200:
			return response
	}

})

export {
	http
}